<?php use_javascript('/js/json_parse.js') ?>
<script type="text/javascript">
<!--

//-->

var i;
var xconfirm;
var destinataires;

function confirmer(){
	$('#notifications').append('<div id="loader"></div>');
	//$('#loader').append('<img src="/images/ajax-loader.gif" alt="' + __('wait please...') + '" id="ajaxloader" />');
	$('#loader').append('<br /><progress id="progressBar" min="0" max="100" value="0"></progress>');
	$('#EditButtonTop').html("");
	$('#DeleteButtonTop').html("");
	$('#EditButtonBottom').html("");
	$('#DeleteButtonBottom').html("");
	
	var xhr = getXmlHttpRequest2();
	xhr.open("POST","<?php print url_for('messages/getDestinataires?id=' . $self['id']); ?>",false);
	xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xhr.send("idDefinition="+<?php print $self->id?>);
	
	var text = xhr.responseText;
	destinataires = json_parse(text);
	$('#progressBar').attr('max',destinataires.length);
	i = 0;
	xconfirm = 0;

	sendOne();
	//document.getElementById('notifications').innerHTML = document.getElementById('notifications').innerHTML + '</ul>';
	
	//document.getElementById('loader').innerHTML = "";
}


function sendOne() {
	xconfirm = 0;
	if(destinataires.length==0){
		$('#loader').remove();
		var text = '<p>Votre message n\'a pas des destinataires!</p>';
		$('#notifications').append(text);
		return '';
	}
	if(i==destinataires.length - 1){
		xconfirm = 1;
	}
	$('#progressBar').val(i);
	var xhr = getXmlHttpRequest2();
	xhr.onreadystatechange = function(){
		if(xhr.readyState == 4) {
			if (xhr.status == 200) {
				var reponse = json_parse(xhr.responseText);
				var bullet = i + 1;
				var reponsetext = '';
				for(var j = 0; j < reponse.length - 1; j++){
					reponsetext = reponsetext + ' ' + reponse[j].result;
				}
				var text = '<p>' + bullet + ' Destinataire : ' + destinataires[i]['prenom'] + ' ' + destinataires[i]['nom'] + ' ' + reponsetext + '</p>';
				$('#notifications').append(text);
			} else {
				var text = bullet + ' Message envoy&eacute; : ' + destinataires[i]['prenom'] + ' ' + destinataires[i]['nom'] + ' ' + ' -- ERREUR PAGE ';
			}
			i++;
			if (i < destinataires.length) {
				sendOne();
			} else {
				$('#bouttonConfirm').html("");
				$('#loader').remove();
			}
		}
	};
	xhr.open("POST","<?php print url_for('messages/sendMessage'); ?>",true);
	xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xhr.send("message_id="+<?php print $self->id?>+"&personne_id="+destinataires[i]['id']+"&confirm="+xconfirm);
}


</script>

